package com.zengqingfa.thread.orderthread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @fileName: CycleBarrierTest2
 * @author: zengqf3
 * @date: 2021-6-26 13:42
 * @description:
 */
public class CycleBarrierTest2 {
    static CyclicBarrier barrier = new CyclicBarrier(5);

    /**
     * Thread-0:到达栅栏
     * Thread-2:到达栅栏
     * Thread-1:到达栅栏
     * Thread-3:到达栅栏
     * Thread-4:到达栅栏
     * Thread-4:穿过栅栏
     * Thread-2:穿过栅栏
     * Thread-2:执行任务
     * Thread-0:穿过栅栏
     * Thread-0:执行任务
     * Thread-3:穿过栅栏
     * Thread-3:执行任务
     * Thread-1:穿过栅栏
     * Thread-1:执行任务
     * Thread-4:执行任务
     *
     * @param args
     */
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    //线程已经到达栅栏
                    System.out.println(Thread.currentThread().getName() + ":" + "到达栅栏");
                    barrier.await();
                    System.out.println(Thread.currentThread().getName() + ":" + "穿过栅栏");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ":" + "执行任务");
            }).start();
        }
    }
}
